﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Service.Model.Context;
using ShortBus;

namespace Service.Workflow.PlayerHeuristic.Command
{
    public class CreatePlayerHeuristicsCommandHandler : IAsyncQueryHandler<CreatePlayerHeuristicsCommand, CreatePlayerHeuristicsCommandResponse>
    {
        private readonly ServiceDbContext dbContext;

        public CreatePlayerHeuristicsCommandHandler(ServiceDbContext serviceDbContext)
        {
            this.dbContext = serviceDbContext;
        }

        public async Task<CreatePlayerHeuristicsCommandResponse> HandleAsync(CreatePlayerHeuristicsCommand command)
        {
            var heuristics = dbContext.Heuristics.Where(h => command.HeuristicIds.Contains(h.HeuristicId));
            var player = dbContext.Players.FirstOrDefault(p => p.PlayerId == command.PlayerId);

            if (player == null)
            {
                throw  new Exception("Error reading player");
            }

            foreach (var heuristic in heuristics)
            {
                var playerHeuristic = new Model.PlayerHeuristic()
                {
                    Heuristic = heuristic,
                    Player = player
                };

                dbContext.PlayerHeuristics.Add(playerHeuristic);
            }

            await dbContext.SaveChangesAsync();

            return new CreatePlayerHeuristicsCommandResponse() {};
        }
    }
}